<template>
	<view class="product-list">
		<!-- 搜索和操作区域 -->
		<view class="search-section">
			<view class="search-filters">
				<view class="search-item">
					<input v-model="searchKeyword" type="text" placeholder="商品名称/编号" class="search-input" />
				</view>
				<view class="search-item">
					<picker mode="selector" :range="categories" range-key="name" @change="handleCategoryFilter">
						<view class="picker-value">
							{{ selectedCategory?.name || '商品分类' }}
						</view>
					</picker>
				</view>
				<view class="search-item">
					<picker
						mode="selector"
						:range="[
							{ name: '全部状态', value: '' },
							{ name: '已上架', value: '1' },
							{ name: '已下架', value: '0' },
						]"
						range-key="name"
						@change="handleStatusFilter"
					>
						<view class="picker-value">
							{{ selectedStatus?.name || '商品状态' }}
						</view>
					</picker>
				</view>
				<button type="primary" size="mini" class="search-btn" @click="handleSearch">搜索</button>
				<button type="default" size="mini" class="reset-btn" @click="handleReset">重置</button>
			</view>
			<view class="operation-btns">
				<button type="primary" class="add-btn" @click="handleAddProduct">
					<text class="btn-icon">+</text>
					新增商品
				</button>
				<button type="default" class="batch-btn" @click="handleBatchOperation">批量操作</button>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="product-cards">
			<view v-for="item in productList" :key="item.id" class="product-card">
				<view class="card-header">
					<view class="product-base">
						<image :src="item.picUrl" mode="aspectFill" class="product-img" />
						<view class="product-info">
							<text class="product-name">{{ item.name }}</text>
							<text class="product-category">{{ item.categoryName }}</text>
						</view>
					</view>
					<text :class="['status-tag', item.status === 1 ? 'active' : 'inactive']">
						{{ item.status === 1 ? '已上架' : '已下架' }}
					</text>
				</view>

				<view class="card-body">
					<view class="info-row">
						<view class="info-item">
							<text class="label">价格</text>
							<text class="value price">¥{{ item.price }}</text>
						</view>
						<view class="info-item">
							<text class="label">库存</text>
							<text class="value">{{ item.stock }}</text>
						</view>
						<view class="info-item">
							<text class="label">销量</text>
							<text class="value">{{ item.salesCount || 0 }}</text>
						</view>
					</view>
				</view>

				<view class="card-footer">
					<view class="action-btns">
						<button type="primary" size="mini" class="action-btn edit" @click="handleEdit(item)">编辑</button>
						<button :type="item.status === 1 ? 'warning' : 'primary'" size="mini" class="action-btn status" @click="handleStatusToggle(item)">
							{{ item.status === 1 ? '下架' : '上架' }}
						</button>
						<button type="default" size="mini" class="action-btn more" @click="handleShowMore(item)">更多</button>
					</view>
				</view>
			</view>

			<view v-if="productList?.length === 0" class="empty-state">
				<image src="/static/images/empty.png" mode="aspectFit" class="empty-icon" />
				<text class="empty-text">暂无商品数据</text>
			</view>
		</view>

		<!-- 分页器 -->
		<view class="pagination">
			<view class="page-info"> 共 {{ total }} 条记录 </view>
			<view class="page-btns">
				<button type="default" size="mini" :disabled="currentPage === 1" @click="handlePageChange(currentPage - 1)">上一页</button>
				<text class="page-number">{{ currentPage }} / {{ totalPages }}</text>
				<button type="default" size="mini" :disabled="isLastPage" @click="handlePageChange(currentPage + 1)">下一页</button>
			</view>
			<view class="page-size">
				<picker mode="selector" :range="[10, 20, 50]" :value="pageSizeIndex" @change="handlePageSizeChange">
					<view class="page-size-text"> {{ pageSize }}条/页 </view>
				</picker>
			</view>
		</view>

		<!-- 更多操作菜单 -->
		<view v-if="showMoreMenu" class="more-menu" :style="moreMenuStyle" @click.stop>
			<view class="menu-item copy" @click="handleCopy(selectedProduct)"> 复制商品 </view>
			<view class="menu-item share" @click="handleShare(selectedProduct)"> 分享商品 </view>
			<view class="menu-item delete" @click="handleDelete(selectedProduct)"> 删除商品 </view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { getSpuPage, updateStatus, deleteSpu } from '@/api/mall/product/spu';
import type { Spu } from '@/api/mall/product/spu';
import type { CategoryVO } from '@/api/mall/product/category';

// 状态定义
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const isLastPage = ref(false);
const productList = ref<Spu[]>([]);

// 筛选相关
const categories = ref<CategoryVO[]>([
	{ id: 1, name: '电子产品', picUrl: '', sort: 1, status: 1 },
	{ id: 2, name: '服装', picUrl: '', sort: 2, status: 1 },
]);
const selectedCategory = ref<CategoryVO>();
const selectedStatus = ref<{ name: string; value: string }>();

// 更多菜单相关
const showMoreMenu = ref(false);
const moreMenuPosition = ref({ x: 0, y: 0 });
const selectedProduct = ref<Spu>();

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value));
const pageSizeIndex = computed(() => {
	const sizes = [10, 20, 50];
	return sizes.indexOf(pageSize.value);
});
const moreMenuStyle = computed(() => ({
	left: `${moreMenuPosition.value.x}px`,
	top: `${moreMenuPosition.value.y}px`,
}));

// 获取商品列表
const loadProductList = async () => {
	try {
		const res = await getSpuPage({
			pageNo: currentPage.value,
			pageSize: pageSize.value,
			name: searchKeyword.value,
			categoryId: selectedCategory.value?.id,
			status: selectedStatus.value?.value ? Number(selectedStatus.value.value) : undefined,
		});
		productList.value = res.list;
		total.value = res.total;
		isLastPage.value = currentPage.value * pageSize.value >= total.value;
	} catch (error) {
		uni.showToast({
			title: '获取商品列表失败',
			icon: 'none',
		});
	}
};

// 搜索相关处理
const handleSearch = () => {
	currentPage.value = 1;
	loadProductList();
};

const handleReset = () => {
	searchKeyword.value = '';
	selectedCategory.value = undefined;
	selectedStatus.value = undefined;
	currentPage.value = 1;
	loadProductList();
};

const handleCategoryFilter = (e: any) => {
	const index = e.detail.value;
	selectedCategory.value = categories.value[index];
};

const handleStatusFilter = (e: any) => {
	const options = [
		{ name: '全部状态', value: '' },
		{ name: '已上架', value: '1' },
		{ name: '已下架', value: '0' },
	];
	selectedStatus.value = options[e.detail.value];
};

// 分页处理
const handlePageChange = (page: number) => {
	if (page < 1 || (isLastPage.value && page > currentPage.value)) return;
	currentPage.value = page;
	loadProductList();
};

const handlePageSizeChange = (e: any) => {
	const sizes = [10, 20, 50];
	pageSize.value = sizes[e.detail.value];
	currentPage.value = 1;
	loadProductList();
};

// 商品操作处理
const handleAddProduct = () => {
	uni.navigateTo({
		url: '/pages/product/views/product-edit',
	});
};

const handleEdit = (item: Spu) => {
	uni.navigateTo({
		url: `/pages/product/views/product-edit?id=${item.id}`,
	});
};

const handleStatusToggle = async (item: Spu) => {
	try {
		await updateStatus({
			id: item.id!,
			status: item.status === 1 ? 0 : 1,
		});
		uni.showToast({
			title: '状态更新成功',
			icon: 'success',
		});
		loadProductList();
	} catch (error) {
		uni.showToast({
			title: '状态更新失败',
			icon: 'none',
		});
	}
};

const handleDelete = async (item: Spu) => {
	uni.showModal({
		title: '确认删除',
		content: '确定要删除该商品吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					await deleteSpu(item.id!);
					uni.showToast({
						title: '删除成功',
						icon: 'success',
					});
					loadProductList();
				} catch (error) {
					uni.showToast({
						title: '删除失败',
						icon: 'none',
					});
				}
			}
		},
	});
};

// 更多菜单相关处理
const handleShowMore = (item: Spu, event: any) => {
	const { clientX, clientY } = event;
	moreMenuPosition.value = { x: clientX, y: clientY };
	selectedProduct.value = item;
	showMoreMenu.value = true;
};

const handleCopy = (item: Spu) => {
	showMoreMenu.value = false;
	uni.navigateTo({
		url: `/pages/product/views/product-edit?copyFrom=${item.id}`,
	});
};

const handleShare = (item: Spu) => {
	showMoreMenu.value = false;
	// TODO: 实现商品分享功能
	uni.showToast({
		title: '分享功能开发中',
		icon: 'none',
	});
};

const handleBatchOperation = () => {
	uni.showActionSheet({
		itemList: ['批量上架', '批量下架', '批量删除'],
		success: (res) => {
			// TODO: 实现批量操作功能
			uni.showToast({
				title: '批量操作功能开发中',
				icon: 'none',
			});
		},
	});
};

// 点击页面任意位置关闭更多菜单
const handlePageClick = () => {
	if (showMoreMenu.value) {
		showMoreMenu.value = false;
	}
};

// 生命周期
onMounted(() => {
	loadProductList();
	// 添加点击事件监听
	document.addEventListener('click', handlePageClick);
});

onUnmounted(() => {
	// 移除点击事件监听
	document.removeEventListener('click', handlePageClick);
});
</script>

<style lang="scss">
.product-list {
	padding: 20rpx;
	background-color: #f5f7fa;
	min-height: 100vh;

	.search-section {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

		.search-filters {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
			margin-bottom: 20rpx;

			.search-item {
				flex: 1;
				min-width: 200rpx;

				.search-input,
				.picker-value {
					height: 64rpx;
					border: 1px solid #dcdfe6;
					border-radius: 4rpx;
					padding: 0 20rpx;
					font-size: 28rpx;
					background-color: #fff;
					display: flex;
					align-items: center;
				}
			}

			.search-btn,
			.reset-btn {
				margin: 0;
				height: 64rpx;
				line-height: 64rpx;
			}
		}

		.operation-btns {
			display: flex;
			gap: 20rpx;

			.add-btn,
			.batch-btn {
				margin: 0;
				height: 72rpx;
				line-height: 72rpx;
				font-size: 28rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.add-btn {
				.btn-icon {
					margin-right: 10rpx;
					font-size: 32rpx;
				}
			}
		}
	}

	.product-cards {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(600rpx, 1fr));
		gap: 20rpx;
		margin-bottom: 20rpx;

		.product-card {
			background-color: #fff;
			border-radius: 8rpx;
			overflow: hidden;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
			transition: all 0.3s ease;

			&:hover {
				transform: translateY(-2rpx);
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
			}

			.card-header {
				padding: 20rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: 1px solid #ebeef5;

				.product-base {
					display: flex;
					align-items: center;
					gap: 20rpx;
					flex: 1;

					.product-img {
						width: 120rpx;
						height: 120rpx;
						border-radius: 8rpx;
						object-fit: cover;
					}

					.product-info {
						flex: 1;
						display: flex;
						flex-direction: column;
						gap: 10rpx;

						.product-name {
							font-size: 28rpx;
							font-weight: bold;
							color: #303133;
						}

						.product-category {
							font-size: 24rpx;
							color: #909399;
						}
					}
				}

				.status-tag {
					padding: 4rpx 16rpx;
					border-radius: 20rpx;
					font-size: 24rpx;

					&.active {
						background-color: #f0f9eb;
						color: #67c23a;
					}

					&.inactive {
						background-color: #f4f4f5;
						color: #909399;
					}
				}
			}

			.card-body {
				padding: 20rpx;

				.info-row {
					display: flex;
					justify-content: space-between;

					.info-item {
						display: flex;
						flex-direction: column;
						align-items: center;
						gap: 10rpx;

						.label {
							font-size: 24rpx;
							color: #909399;
						}

						.value {
							font-size: 28rpx;
							color: #606266;

							&.price {
								color: #f56c6c;
								font-weight: bold;
							}
						}
					}
				}
			}

			.card-footer {
				padding: 20rpx;
				border-top: 1px solid #ebeef5;

				.action-btns {
					display: flex;
					justify-content: flex-end;
					gap: 20rpx;

					.action-btn {
						margin: 0;
						min-width: 120rpx;
						font-size: 24rpx;

						&.edit {
							background-color: #409eff;
							border-color: #409eff;
						}

						&.status {
							&[type='warning'] {
								background-color: #e6a23c;
								border-color: #e6a23c;
							}
						}
					}
				}
			}
		}
	}

	.empty-state {
		background-color: #fff;
		border-radius: 8rpx;
		padding: 60rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

		.empty-icon {
			width: 200rpx;
			height: 200rpx;
			opacity: 0.5;
		}

		.empty-text {
			font-size: 28rpx;
			color: #909399;
		}
	}

	.pagination {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 8rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

		.page-info {
			font-size: 24rpx;
			color: #909399;
		}

		.page-btns {
			display: flex;
			align-items: center;
			gap: 20rpx;

			button {
				margin: 0;
				font-size: 24rpx;

				&[disabled] {
					background-color: #f5f7fa;
					border-color: #dcdfe6;
					color: #c0c4cc;
				}
			}

			.page-number {
				font-size: 24rpx;
				color: #606266;
			}
		}

		.page-size {
			.page-size-text {
				font-size: 24rpx;
				color: #606266;
				padding: 10rpx 20rpx;
				border: 1px solid #dcdfe6;
				border-radius: 4rpx;
				cursor: pointer;

				&:hover {
					border-color: #c0c4cc;
				}
			}
		}
	}

	.more-menu {
		position: fixed;
		background-color: #fff;
		border-radius: 4rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		z-index: 100;
		min-width: 160rpx;

		.menu-item {
			padding: 20rpx 30rpx;
			font-size: 28rpx;
			cursor: pointer;
			transition: all 0.3s ease;

			&:hover {
				background-color: #f5f7fa;
			}

			&.copy {
				color: #409eff;
			}

			&.share {
				color: #67c23a;
			}

			&.delete {
				color: #f56c6c;
			}
		}
	}
}
</style>
